package com.naxiangfish.cn.naxiangfish;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.naxiangfish.cn.R;
import com.naxiangfish.cn.board.BoardCastUtils;
import com.naxiangfish.cn.board.PrensentView;
import com.naxiangfish.cn.constant.ConstantUtils;
import com.naxiangfish.cn.utils.AppManager;
import com.naxiangfish.cn.utils.Utils;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.util.ArrayList;
import java.util.List;

public class BaseActivity extends AppCompatActivity implements PrensentView {
    private LinearLayout   mTitleLinear;
    private LinearLayout   mHandLinear;
    private LinearLayout   mRelatContent;
    private LinearLayout   mHandRelat;
    private BoardCastUtils mCastUtils;
    private static final int MY_SINGLE        = 100;
    private static final int MY_PERMISIONLIST = 101;
    private List<String> mPermissionList;
    String[] permissionss = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };
    private SoundPool mSoundPool;
    private int       mDuanSound;
    private int       mYuluSound;
    private boolean haveMusic = true;


    private RelativeLayout mLeft;
    private RelativeLayout mRight;
    private TextView       mTitle;
    private RelativeLayout mRelatLeft;
    private RelativeLayout mRelatRight;
    private TextView       mRelatTitle;

    //  默认设置为线性排列布局
    private int showStyle = ConstantUtils.LINEARSHOW;
    private PopupWindow       mPopupWindow;
    private ImageView         mPopimageView;
    private AnimationDrawable mAnimation;
    private LinearLayout mMianlinear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //解决华为手机沉侵式状态栏
        getWindow().getDecorView().setFitsSystemWindows(true);
        //透明状态栏 @顶部
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //透明导航栏 @底部    这一句不要加，目的是防止沉浸式状态栏和部分底部自带虚拟按键的手机（比如华为）发生冲突，注释掉就好了
        //        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);


        //待测试  https://blog.csdn.net/lijunhuayc/article/details/53031898
//        if (isApplyKitKatTranslucency()) {
//            setSystemBarTintDrawable(getResources().getDrawable(R.color.colorPrimary));
//        }

        setContentView(R.layout.activity_base);

        //添加到栈中,将所有的Activity到集合当中
        AppManager.getInstance().addActivity(this);


        //注册监听网络等这里还需要再加一个String flg来确定请求框架，暂时只是留个接口
        //        mCastUtils = new BoardCastUtils();
        //        mCastUtils.netWork(this);
        //        mCastUtils.sreamWork(this);

        //获取6.0权限
        getListPermissions(permissionss);


        mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
        //预加载音乐
        mDuanSound = mSoundPool.load(this, R.raw.duan, 1);
        mYuluSound = mSoundPool.load(this, R.raw.yulu, 1);

        mMianlinear= (LinearLayout) findViewById(R.id.mianlinear);

        //获取StatusBar
        mTitleLinear = (LinearLayout) findViewById(R.id.titlelinear);


        //不做整体背景的时候显示使用
        mHandLinear = (LinearLayout) findViewById(R.id.handlinear);


        //做整体背景的时候显示
        mRelatContent = (LinearLayout) findViewById(R.id.content_layout);
        mHandRelat = (LinearLayout) findViewById(R.id.handrealat);


        mLeft = (RelativeLayout) findViewById(R.id.left);
        mRight = (RelativeLayout) findViewById(R.id.right);
        mTitle = (TextView) findViewById(R.id.titletext);


        mRelatLeft = (RelativeLayout) findViewById(R.id.relatleft);
        mRelatRight = (RelativeLayout) findViewById(R.id.relatright);
        mRelatTitle = (TextView) findViewById(R.id.relattitletext);


        //设置StatusBar高度
        //        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,300);
        //        mTitleLinear.setLayoutParams(params);

        //设置界面的展示方式
        showState();

        //初始化动画
        initAnimationView();
    }



    /**
     * 设置子类的布局，传一个layoutID;如：R.layout.activity_base
     * setContentView_V(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param layoutID void
     * @throws
     * @since 1.0.0
     */
    public void setContentViewShow(int layoutID) {
        // 获得inflater
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // 把继承该BaseAcitivyt的layoutID放进来 显示

        View view = inflater.inflate(layoutID, null);
        // content_layout.addView(view);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        // content_layout.addView(view, layoutParams);
        view.setLayoutParams(layoutParams);
        if (null != mRelatContent) {
            mRelatContent.addView(view);
        }
    }


    //播放音乐
    public void playMusic() {
        //播放长声音
        //        mSoundPool.play(mYuluSound,1,1,0,0,1);
        if (haveMusic) {
            mSoundPool.play(mDuanSound, 1, 1, 0, 0, 1);
        }

    }

    //获取网络类型
    @Override
    public void onNetChange(int netMobile) {
        System.out.println("网络类型：====" + netMobile);
    }

    //获取屏幕状态
    @Override
    public void onScreamState(int flg) {
        System.out.println("屏幕明暗情况：====" + flg);
    }
    //    @Override
    //    protected void onDestroy() {
    //        super.onDestroy();
    //        mCastUtils.unRegistNetWork(BaseActivity.this);
    //        mCastUtils.unRegistScreamWork(BaseActivity.this);
    //    }

    /**
     * @param permision 需要的单个权限
     */
    public boolean getSinglePermission(String permision) {
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, permision) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{permision},
                        MY_SINGLE);
                return false;
            }else {
                return true;
            }
        }else {
            return true;
        }
    }

    public void getListPermissions(String[] permissions) {

        // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
        if (mPermissionList == null) {
            mPermissionList = new ArrayList<>();
        } else {
            mPermissionList.clear();
        }
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (!mPermissionList.isEmpty()) {
                //将List转为数组
                String[] permissionarrs = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(BaseActivity.this, permissionarrs, MY_PERMISIONLIST);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //单项回调
        if (requestCode == MY_SINGLE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //                    showToast("权限已申请");
            } else {
                //                    showToast("权限已拒绝");
                //判断是否勾选禁止后不再询问
                boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this, permissions[0]);
                if (!showRequestPermission) {
                    Intent intent = new Intent(
                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }
            }
        } else if (requestCode == MY_PERMISIONLIST) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this, permissions[i]);
                    if (showRequestPermission) {
                        //                        Intent intent = new Intent(
                        //                                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        //                        intent.setData(Uri.parse("package:" + getPackageName()));
                        //                        startActivity(intent);

                        Utils.goToSetting();
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getInstance().finishActivity(this); //从栈中移除
    }

    //展示方式
    public void setWindShowStyle(int munber) {
        showStyle = munber;
        //设置界面的展示方式
        showState();
    }

    private void showState() {
        switch (showStyle) {
            case ConstantUtils.LINEARSHOW:
                mTitleLinear.setVisibility(View.VISIBLE);
                mHandLinear.setVisibility(View.VISIBLE);
                mHandRelat.setVisibility(View.GONE);
                break;
            case ConstantUtils.RELEATSHOW:
                mTitleLinear.setVisibility(View.GONE);
                mHandLinear.setVisibility(View.GONE);
                mHandRelat.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * @param clazz   要跳转到的类
     * @param isFinsh 是否销毁当前界面
     */
    public void skipOtherActivity(Class clazz, boolean isFinsh) {

        startActivity(new Intent(BaseActivity.this, clazz));
        if (isFinsh) {

        }

    }

    /**
     * @return 线性布局的头布局
     */
    public LinearLayout getHandLinear() {
        if (mHandLinear == null) {
            mHandLinear = (LinearLayout) findViewById(R.id.handlinear);
            return mHandLinear;
        }
        return mHandLinear;
    }

    /**
     * @return 相对布局的头布局
     */
    public LinearLayout getHandRelat() {
        if (mHandRelat == null) {
            mHandRelat = (LinearLayout) findViewById(R.id.handrealat);
            return mHandRelat;
        }
        return mHandRelat;
    }

    /**
     * 设置左边按钮里是文字 setLeftShow(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @throws
     * @since 1.0.0
     */
    public void setLeftShow(int tag, int resID) {
        if (null == mLeft) {
            return;
        }
        mLeft.removeAllViews();
        mLeft.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mLeft.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            mLeft.addView(view, params);
        } else if (tag == 3) {
            View view = getLayoutInflater().inflate(R.layout.weightback, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            mLeft.addView(view, params);
        }
    }

    public void setTitleText(String title) {
        mTitle.setText(title);
        mRelatTitle.setText(title);
    }

    /**
     * 设置右边边按钮里是文字 setRightShow(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @throws
     * @since 1.0.0
     */
    public void setRightShow(int tag, int resID) {
        if (null == mRight) {
            return;
        }
        mRight.removeAllViews();
        mRight.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRight.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRight.addView(view, params);
        }
    }

    public void setRelatLeftShow(int tag, int resID) {
        if (null == mRelatLeft) {
            return;
        }
        mRelatLeft.removeAllViews();
        mRelatLeft.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRelatLeft.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            mRelatLeft.addView(view, params);
        } else if (tag == 3) {
            View view = getLayoutInflater().inflate(R.layout.weightback, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            mRelatLeft.addView(view, params);
        }
    }

    public void setRelatRightShow(int tag, int resID) {

        if (null == mRelatRight) {
            return;
        }
        mRelatRight.removeAllViews();
        mRelatRight.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRelatRight.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRelatRight.addView(view, params);
        }
    }

    //判断是否有网络
    public boolean isConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    //设置加载动画
    public void startLoadingAnimation() {
        setBackgroundAlpha(0.4f);//设置屏幕透明度
        mMianlinear.post(new Runnable() {
            @Override
            public void run() {
                mPopupWindow.showAtLocation(mMianlinear, Gravity.CENTER,0,0);
                //开始动画
                mPopimageView.post(new Runnable() {
                    @Override
                    public void run() {
                        mAnimation.start();
                    }
                });
            }
        });

    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    //初始化动画view
    private void initAnimationView() {
        //引入popopwindow的加载动画的布局
        if (mPopupWindow == null) {
            View popView = LayoutInflater.from(BaseActivity.this).inflate(R.layout.refrsh_layout, null);
            //加载中的动画已经彻底完成了
            mPopimageView = (ImageView) popView.findViewById(R.id.popowimage);
            mPopimageView.setBackgroundResource(R.drawable.loading);
            mAnimation = (AnimationDrawable) mPopimageView.getBackground();
            mPopupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        }

        // 设置弹出动画
        //        popupWindow.setAnimationStyle(R.style.AnimationFadeBottom);
        //显示popupwindow
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());


        //PopupWindow外部不消失并且不穿透事件
        mPopupWindow.setFocusable(true);
        //设置点击外部对话框消失
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
                mAnimation.stop();
            }
        });
    }

    //隐藏加载动画
    public void stopLoadingAnimation(){
        if(null != mPopupWindow && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
            mAnimation.stop();
            setBackgroundAlpha(1.0f);
        }


    }

    //默认返回true
    protected boolean isApplyKitKatTranslucency() {
        return true;
    }
    /**
     * use SytemBarTintManager
     *      https://blog.csdn.net/lijunhuayc/article/details/53031898
     * @param tintDrawable
     */
    protected void setSystemBarTintDrawable(Drawable tintDrawable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager mTintManager = new SystemBarTintManager(this);
            if (tintDrawable != null) {
                mTintManager.setStatusBarTintEnabled(true);
                mTintManager.setTintDrawable(tintDrawable);
            } else {
                mTintManager.setStatusBarTintEnabled(false);
                mTintManager.setTintDrawable(null);
            }
        }

    }

}
